$(function () {
    init();
    initDate();
  //多选框
	
})
$(document).on('change', 'input:checkbox.master', function(){
		if($(this).prop('checked')){
			$('input:checkbox.slaver').prop('checked', 'checked');
		}else{
			$('input:checkbox.slaver').prop('checked', '');
		}
	})
function excleUser(){
	
}
/**
 * 回车检索
 * @returns
 */
function search(){
	if(event.keyCode==13){
		toSearch();
	}
}
function toSearch(){
	init();
}
/**
 * 初始化时间控件
 * @returns
 */
function initDate(){
	$("#reservation").daterangepicker({
        locale : {
            format: 'YYYY-MM-DD',
            separator:' 到 ',
            applyLabel : '确定',
            cancelLabel : '取消',
            customRangeLabel : '自定义',
            daysOfWeek : [ '日', '一', '二', '三', '四', '五', '六' ],
            monthNames : [ '一月', '二月', '三月', '四月', '五月', '六月',
                '七月', '八月', '九月', '十月', '十一月', '十二月' ],
            firstDay : 1
        },
        ranges: {
            '今天': [moment().startOf('day'), moment()],
            '昨天': [moment().subtract(1,'days').startOf('day'), moment().subtract(1,'days').endOf('day')],
            '本周': [moment().startOf("week").add(1,'days'),moment().endOf("week").add(1,'days')],
            '上周': [moment().subtract(1,'weeks').startOf("week").add(1,'days'),moment().subtract(1,'weeks').endOf("week").endOf("week").add(1,'days')],
            '本月': [moment().startOf("month"),moment().endOf("month")],
            '上个月': [moment().subtract(1,"month").startOf("month"),moment().subtract(1,"month").endOf("month")],
            '最近7天': [moment().subtract(6,'days'), moment()],
            '最近30天': [moment().subtract(29,'days'), moment()]
        },
        applyClass:'btn-primary',
        alwaysShowCalendars: true,
        autoclose:true
	});
}
/**
 * 修改用户状态
 * @returns
 */
function chooseUser(val,flag){
	var attr = $("#span"+val).attr("class");
	if(attr == "btn btn-xs btn-nouse"){
		flag = 1;
	}else{
		flag = 0;
	}
	$.ajax({
        url: ctx + '/user/updateRecord',
        type: 'POST',
        data: {
        	userId:val,
        	enable:flag
        },
        dataType: 'json',
        success: function (data) {
        	/*if(data.status == 'success' && flag == 1){
        		$("#span"+val).removeClass("btn-nouse").addClass("btn-use");
        		$("#span"+val).html('<i class="fa fa-check-circle-o"></i> 启用');
        	}
        	if(data.status == 'success' && flag == 0){
        		$("#span"+val).removeClass("btn-use").addClass("btn-nouse");
        		$("#span"+val).html('<i class="fa fa-ban"></i> 禁用');
        	}*/
        	init();
        }
	});
}


function validateForm() {
    $.ajax({
        url: __root__ + '/user/addNewUser',
        type: 'POST',
        data: $('#myform').serialize(),
        dataType: 'json',
        success: function (data) {
            if (data.status == "success"){
            	toastr.success(data.msg);
            }else{
            	toastr.error(data.msg);
            }
                
        },
        error: function (response) {
            alert("系统错误");
        }
    });
    return false;
}


//文件上传
function uploadFile(t) {

    var _this = $(t);

    var formData = new FormData();

    formData.append('file', _this[0].files[0]);

    var inputName = _this.attr('extra');

    $.ajax({
        url: __root__ + '/file/uploadFile',
        type: 'POST',
        data: formData,
        async: false,
        cache: false,
        contentType: false,
        processData: false,
        dataType: 'json',
        success: function (data) {
            if (data.status == "success") {
                alert(data.msg);
            } else {
                alert(data.msg);
            }
        },
        error: function () {
            alert('系统错误');
        }
    });
};
/**
 * 回调函数
 * @param sSource
 * @param aoData
 * @param fnCallback
 * @returns
 */
function retrieveData(sSource, aoData, fnCallback, oSettings ){
	/**
	 * 参数添加
	 */
	aoData.push( { "name": "pageNum", "value": (Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength )+1) });
	aoData.push( { "name": "pageSize", "value": oSettings._iDisplayLength });	
	aoData.push( { "name": "beginTime", "value": $("#reservation").val().split("到")[0] } );
	aoData.push( { "name": "endTime", "value": $("#reservation").val().split("到")[1] } );
	aoData.push( { "name": "enable", "value": $("#enable").val() } );
	aoData.push( { "name": "searchVal", "value": $("#searchVal").val()} );
		
	$.ajax({
		"type" : "Post",
		"url" : sSource,
		"dataType" : "json",
		"data" : aoData,
		"success" : function(resp) {
			fnCallback(resp.returnObject);
		}
	});
	//每页显示记录数
	$('.dataTables_info').parent().append($('.dataTables_length'));
}

/**
 * 删除操作
 * @param val
 * @returns
 */
function del(val){
	$.ajax({
        url: ctx + '/user/deleteRecord',
        type: 'POST',
        data: {
        	userId:val,
        },
        dataType: 'json',
        success: function (data) {
        	if(data.status == 'success'){
        		init();
        		toastr.success(data.msg);
        	}
        }
	});
}
/**
 * 跳转编辑页面
 * @param val
 * @returns
 */
function edit(val){
	 loadHtml('/user/toEditUser/'+val); 
}
function modifyPwd(userId){
	if(userId==''||userId==null){
		toastr.error('用户Id为空,不能修改');
		return false;
	}
	$('#changeUserPassword input[name=userId]').val(userId);
	$('.changeUserPassword').modal('show');
}
//表单验证
$('#changeUserPassword').bootstrapValidator({
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
        newPassword: {
            validators: {
                stringLength: {
                    min: 6,
                    max: 30,
                    message: '密码长度最小6位最长30位'
                },
                regexp: {
                    regexp: /^[a-zA-Z0-9_\.]+$/,
                    message: '密码只能有数字、字母、下划线组成'
                }
            }
        },
        affirmPassword: {
            validators: {
                stringLength: {
                    min: 6,
                    max: 30,
                    message: '密码长度最小6位最长30位'
                },
                identical: {
                    field: 'newPassword',
                    message: '两次密码输入不一致'
                },
                regexp: {
                    regexp: /^[a-zA-Z0-9_\.]+$/,
                    message: '密码只能有数字、字母、下划线组成'
                }
            }
        },
    },
        submitHandler: function (validator, form, submitButton) {
            $.ajax({
            	url: ctx + "/user/changePwd",
                type: 'POST',
                data:  $('#changeUserPassword').serialize(),
                dataType: 'json',
                success: function (data) {
                    if (data.msg){
                    	toastr.error(data.msg);
                    }else{
                    	$('.changeUserPassword').modal('hide');
                    	toastr.success('修改成功');
                    }
                },
                error: function (response) {
                	toastr.error("系统错误");
                }
            });
            return false;
        }
});
